package com.jiankangjin.appspos.services.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiankangjin.appspos.dao.info.IAccountDao;
import com.jiankangjin.appspos.entity.info.IsTipOrdeAcountEntity;
import com.jiankangjin.appspos.entity.info.NoticeCountEntity;
import com.jiankangjin.appspos.services.UserServices;
import com.jiankangjin.appspos.util.ResourceMap;
import com.jiankangjin.appspos.vo.CertiCodeResendVo;
import com.jiankangjin.appspos.vo.GetUserInfoVo;
import com.jiankangjin.appspos.vo.UpdPasswordVo;
import com.jiankangjin.appspos.vo.UserLoginVo;
import com.jiankangjin.appspos.vo.UserLogoutVo;
import com.jiankangjin.appspos.vo.ValidateUserCertiVo;
import com.jiankangjin.appspos.vo.ValidateUserCertiVo.MerInfo.MerBusiType;
import com.jiankangjin.httpclient.HttpClient;



/**  
 * 用户登录<br>
 * 第一步：获取图片验证码<br>
 * 第二步：帐号，密码，验证码登陆<br>
 * 第三步：发送短信码<br>
 * 第四步：验证短信码 <br>
 */
@Service
public class UserServicesImpl implements UserServices{
	@Autowired
	private IAccountDao accountDao;

	public IAccountDao getAccountDao() {
		return accountDao;
	}

	public void setAccountDao(IAccountDao accountDao) {
		this.accountDao = accountDao;
	}
	private static final transient Log logger = LogFactory.getLog(UserServicesImpl.class);
	
	/**
	 * 获得图片验证码后	用户登录
	 */
	@Override
	public UserLoginVo userLogin(String tmpSsn, String validateCode,
			String loginVouche, String loginPassword, String terminalType,
			String terminalVer, String terminalId) {
		UserLoginVo userLoginVo = new UserLoginVo();
		try {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("tmpSsn", tmpSsn);
			params.put("username", loginVouche);
			params.put("password", loginPassword);
			params.put("imgCode", validateCode);
			params.put("terminalType", terminalType);
			params.put("terminalVersion", terminalVer);
			params.put("terminalId", terminalId);
			params.put("terminalIP", "appSPOS_value");
			params.put("appId", "appSPOS_value");
			params.put("sign", "appSPOS_userLogin_sign");
			if (logger.isInfoEnabled()) {
				logger.info("调帐户系统用户登陆:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/accmanage/validate_user_info", params);
			if (logger.isInfoEnabled()) {
				logger.info("帐户系统用户登陆返回:" + map);
			}
			if (map == null) {
				userLoginVo.setResp_status("9999");
				userLoginVo.setMsg("帐户系统用户登陆返回空");
				return userLoginVo;
			}
			String[] resTip = ResourceMap.getArray("A_validate_user_info_" + (String) map.get("status"));
			userLoginVo.setResp_status(resTip[0]);
			userLoginVo.setMsg(resTip[1]);
			userLoginVo.setToken_low((String) map.get("tmpToken"));
			userLoginVo.setTmpSsn((String) map.get("tmpSsn"));
			userLoginVo.setMobilePhone((String) map.get("mobilePhone"));
			userLoginVo.setDownloadUrl((String) map.get("downloadUrl"));
			userLoginVo.setSign("appSPOS_userLogin_sign");
			return userLoginVo;
		} catch (Exception e) {
			logger.error(this, e);
			userLoginVo.setResp_status("9999");
			userLoginVo.setMsg("调用接口失败");
			return userLoginVo;
		}
	}

	/**
	 * 登出
	 */
	@Override
	public UserLogoutVo userLogout(String token) {
		UserLogoutVo userLogoutVo = new UserLogoutVo();
		try {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("token", token);
			if (logger.isInfoEnabled()) {
				logger.info("调帐户系统用户注销:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/accmanage/user_logout", params);
			if (logger.isInfoEnabled()) {
				logger.info("帐户系统用户注销返回:" + map);
			}
			if (map == null) {
				userLogoutVo.setResp_status("9999");
				userLogoutVo.setMsg("帐户系统用户注销返回空");
				return userLogoutVo;
			}
			String[] resTip = ResourceMap.getArray("A_user_logout_" + (String) map.get("status"));
			userLogoutVo.setResp_status(resTip[0]);
			userLogoutVo.setMsg(resTip[1]);
			userLogoutVo.setSign("appSPOS_userLogout_sign");
			return userLogoutVo;
		} catch (Exception e) {
			logger.error(this, e);
			return userLogoutVo;
		}
	}

	/**
	 * 登陆第二步，申请发送手机验证码验证码
	 */
	@Override
	public CertiCodeResendVo certiCodeResend(String tokenLow) {
		CertiCodeResendVo certiCodeResendVo = new CertiCodeResendVo();
		try {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("token", tokenLow);
			if (logger.isInfoEnabled()) {
				logger.info("调帐户系统重发验证码:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/accmanage/reget_mobi_ph", params);
			if (logger.isInfoEnabled()) {
				logger.info("帐户系统重发验证码返回:" + map);
			}
			if(map == null) {
				certiCodeResendVo.setResp_status("9999");
				certiCodeResendVo.setMsg("帐户系统重发验证码返回空");
				return certiCodeResendVo;
			}
			String[] resTip = ResourceMap.getArray("A_reget_mobi_ph_" + (String) map.get("status"));
			certiCodeResendVo.setResp_status(resTip[0]);
			certiCodeResendVo.setMsg(resTip[1]);
			certiCodeResendVo.setToken_low((String) map.get("tmpToken"));
			certiCodeResendVo.setSign("appSPOS_certiCodeResend_sign");
			return certiCodeResendVo;
		} catch (Exception e) {
			logger.error(this, e);
			return certiCodeResendVo;
		}
	}

	/**
	 * 登陆第三步，验证短信码，身份校验请求
	 * @return 
	 */
	@Override
	public ValidateUserCertiVo validateUserCerti(String tokenLow, String certiCode) {
		ValidateUserCertiVo validateUserCertiVo = new ValidateUserCertiVo();
		
		try {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("tmpToken", tokenLow);
			params.put("smsCode", certiCode);
			if (logger.isInfoEnabled()) {
				logger.info("调帐户系统校验身份:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/accmanage/user_login", params);
			if (logger.isInfoEnabled()) {
				logger.info("帐户系统校验身份返回:" + map);
			}
			if (map == null) {
				validateUserCertiVo.setResp_status("9999");
				validateUserCertiVo.setMsg("帐户系统校验身份返回空");
				return validateUserCertiVo;
			}
			//获取最新的公告数量
			List list = this.accountDao.getNewNotice();
			int notice_Acount =0; //最新公告数量
			for(int i =0;i<list.size();i++){
				NoticeCountEntity NoticeCountEntity = (NoticeCountEntity) list.get(i);
				notice_Acount += NoticeCountEntity.getNotice_amout();
			}
			
			//获取用户信息(operatorId)
			String token = (String) map.get("token");
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("token", token);
			Map<String, Object> operatorMap = HttpClient.getInstance()
					.doPOSTgetHashMap("/accmanage/query_user_info", param);
			if (operatorMap != null) {
				//通过用户信息id（operatorId）获取商户信息
				String operatorId =(String)operatorMap.get("userid");
				HashMap<String, Object> param1 = new HashMap<String, Object>();
				param1.put("operatorId", operatorId);
				//param1.put("operatorId", "2c9071dc473e927401473e9274ab0001");
				Map<String,Object>map1 =HttpClient.getInstance().doPOSTgetHashMap("/transSystem/getIsTipOrder", param1);
				if(map1 != null){
					//获取用户的操作权限，用于客户端权限判定（退款是否显示，是否可以审批）
					List <ValidateUserCertiVo.MerPermInfo[]> MerPermInfoList = (List <ValidateUserCertiVo.MerPermInfo[]>) map1.get("merPermInfo");
					if(MerPermInfoList != null){
						ValidateUserCertiVo.MerPermInfo[] MerPermInfoSz = new ValidateUserCertiVo.MerPermInfo[MerPermInfoList.size()];
						for(int j=0;j<MerPermInfoList.size();j++){
							ValidateUserCertiVo.MerPermInfo MerPermInfoDy = validateUserCertiVo.new MerPermInfo();
							Object ss= (Object)MerPermInfoList.get(j);
							String ssd = ss.toString();
							String[] stringArr= ssd.split(",");
							String permCde = stringArr[0].split("=")[1];
							String permName = stringArr[1].split("=")[1];
							permName = permName.substring(0, permName.length()-1);
							MerPermInfoDy.setPermCde(permCde);
							MerPermInfoDy.setPermName(permName);
							MerPermInfoSz[j] = MerPermInfoDy;
						}
						validateUserCertiVo.setMerPermInfo(MerPermInfoSz);
					}
					//获取商户信息列表
					List<IsTipOrdeAcountEntity> merInfoList= (List<IsTipOrdeAcountEntity>)map1.get("merInfo");
					if(merInfoList !=null){
					ValidateUserCertiVo.MerInfo[] merInfo = new ValidateUserCertiVo.MerInfo[merInfoList.size()];
					for(int i=0;i<merInfoList.size();i++){
						ValidateUserCertiVo.MerInfo merInfo1 = validateUserCertiVo.new MerInfo();
						Map<String,Object> mape= (Map<String, Object>) merInfoList.get(i);
						//获取商户的商户名及订单未补全的数量
						String merName =(String)mape.get("merName");
						String IsTipAcount =(String)mape.get("isTipAcount");
						merInfo1.setMer_Name(merName);
						merInfo1.setMer_logo("");
						merInfo1.setIs_Tip_Acount(IsTipAcount);
						merInfo1.setNotice_Acount(String.valueOf(notice_Acount));
						
						//获取商户支持的业务类型
						//[{busl_type=20000001, busl_type_name=普通门诊}, {busl_type=20000001, busl_type_name=普通门诊}]
						List <ValidateUserCertiVo.MerInfo.MerBusiType[]> merBusiTypeList = (List<MerBusiType[]>) mape.get("merBusiType");
						ValidateUserCertiVo.MerInfo.MerBusiType[] merBusiTypeSz = new ValidateUserCertiVo.MerInfo.MerBusiType[merBusiTypeList.size()];
						for(int j =0;j<merBusiTypeList.size();j++){
							ValidateUserCertiVo.MerInfo.MerBusiType MerBusiTypeDy = validateUserCertiVo.new MerInfo().new MerBusiType();
							Object ss= (Object)merBusiTypeList.get(j);
							String ssd = ss.toString();
							String[] stringArr= ssd.split(",");
							String busi_type = stringArr[0].split("=")[1];
							String busi_name = stringArr[1].split("=")[1];   
							busi_name = busi_name.substring(0, busi_name.length()-1);
							//获取上海支持的业务类型所拥有的商品类型
							String feeArr = ssd.split("feeTypeInfo=")[1];
							feeArr =feeArr.substring(0,feeArr.length()-1);
							//[{fee_type=1004, fee_type_name=挂号费}, {fee_type=1003, fee_type_name=化验费}, {fee_type=1007, fee_type_name=理疗费}, {fee_type=1002, fee_type_name=医药费}]
							String ssee[] = feeArr.split("},");
							ValidateUserCertiVo.MerInfo.MerBusiType.FeeTypeInfo[] feeTypeInfoSz = new ValidateUserCertiVo.MerInfo.MerBusiType.FeeTypeInfo[ssee.length];
							for(int s =0;s<ssee.length;s++){
								ValidateUserCertiVo.MerInfo.MerBusiType.FeeTypeInfo FeeTypeInfoDx = validateUserCertiVo.new MerInfo().new MerBusiType().new FeeTypeInfo();
								//[{fee_type=1004, fee_type_name=挂号费
								String[] fee_typeSz = ssee[s].split(",");
								String fee_type = fee_typeSz[0].split("=")[1];
								String fee_type_name =fee_typeSz[1].split("=")[1];
								if(s+1 ==ssee.length){
									 fee_type_name =fee_type_name.substring(0, fee_type_name.length()-2);
								}
								FeeTypeInfoDx.setFee_type(fee_type);
								FeeTypeInfoDx.setFee_type_name(fee_type_name);
								feeTypeInfoSz[s] = FeeTypeInfoDx;
							}
							MerBusiTypeDy.setFeeTypeInfo(feeTypeInfoSz);
					        MerBusiTypeDy.setBusl_type(busi_type);
							MerBusiTypeDy.setBusl_type_name(busi_name);
							merBusiTypeSz[j] = MerBusiTypeDy;
						}
						merInfo1.setMerBusiType(merBusiTypeSz);
						merInfo[i] = merInfo1;
					}
					validateUserCertiVo.setMerInfo(merInfo);
				 }
					
				}
			}
			String[] resTip = ResourceMap.getArray("A_user_login_" + (String) map.get("status"));
			validateUserCertiVo.setResp_status(resTip[0]);
			validateUserCertiVo.setMsg(resTip[1]);
			validateUserCertiVo.setToken((String)map.get("token"));
			validateUserCertiVo.setValid_time((String)map.get("tokenValidTime"));
			validateUserCertiVo.setGesture_password((String)map.get("gesturePwd"));
			validateUserCertiVo.setUser_name((String)map.get("username"));
			validateUserCertiVo.setUser_logo((String)map.get("userLogo"));
			validateUserCertiVo.setLastLoginTime((String)map.get("lastLoginTime"));
			//validateUserCertiVo.setNotice_Acount(notice_Acount);
//			validateUserCertiVo.setUser_role("");//返回中未定义
//			validateUserCertiVo.setMerchant_logo("");//返回中未定义
//			validateUserCertiVo.setMerchant_name("");//返回中未定义
			validateUserCertiVo.setSign("appSPOS_validateUserCerti_sign");
			return validateUserCertiVo;
		} catch (Exception e) {
			logger.error(this, e);
			return validateUserCertiVo;
		}
	}


	/**
	 * 密码更新
	 */
	@Override
	public UpdPasswordVo updPassword(String token, String oldPassword, String newPassword) {
		UpdPasswordVo updPasswordVo = new UpdPasswordVo();
		try {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("token", token);
			params.put("oldPwd", oldPassword);
			params.put("newPwd", newPassword);
			if (logger.isInfoEnabled()) {
				logger.info("调帐户系统更新密码:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/accmanage/change_pwd", params);
			if (logger.isInfoEnabled()) {
				logger.info("帐户系统更新密码返回:" + map);
			}
			if(map == null) {
				updPasswordVo.setResp_status("9999");
				updPasswordVo.setMsg("调帐户系统更新密码空");
				return updPasswordVo;
			}
			String[] resTip = ResourceMap.getArray("A_change_pwd_" + (String) map.get("status"));
			updPasswordVo.setResp_status(resTip[0]);
			updPasswordVo.setMsg(resTip[1]);	
			updPasswordVo.setSign("appSPOS_updPassword_sign");
			return updPasswordVo;
		} catch (Exception e) {
			logger.error(this, e);
			return updPasswordVo;
		}
	}

	/**
	 * 下载用户信息
	 */
	@Override
	public GetUserInfoVo getUserInfo(String token) {
		GetUserInfoVo getUserInfoVo=new GetUserInfoVo();
		try {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("token", token);
			if (logger.isInfoEnabled()) {
				logger.info("调帐户系统下载用户信息:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/accmanage/query_user_info", params);
			if (logger.isInfoEnabled()) {
				logger.info("帐户系统下载用户信息返回:" + map);
			}
			if (map == null) {
				getUserInfoVo.setResp_status("9999");
				getUserInfoVo.setMsg("帐户系统下载用户信息返回空");
				return getUserInfoVo;
			}
			String[] resTip = ResourceMap.getArray("A_query_user_info_" + (String) map.get("status"));
			getUserInfoVo.setResp_status(resTip[0]);
			getUserInfoVo.setMsg(resTip[1]);
			getUserInfoVo.setToken((String) map.get("token"));
			getUserInfoVo.setUser_name((String) map.get("username"));
            // userid设置
            getUserInfoVo.setUuid((String)map.get("userid"));
			getUserInfoVo.setUser_gender((String) map.get("gender"));
			getUserInfoVo.setUser_addr((String) map.get("address"));
			getUserInfoVo.setSign("appSPOS_getUserInfo_sign");
			return getUserInfoVo;
		} catch (Exception e) {
			logger.error(this, e);
			return getUserInfoVo;
		}
	}

}
